package com.sky.checkutil.util;

import com.alibaba.excel.EasyExcel;
import com.sky.checkutil.config.CustomCellWriteHeightConfig;
import com.sky.checkutil.domain.CheckParam;
import com.sky.checkutil.domain.CheckVO;
import com.sky.checkutil.javadoc.ExtClassDoc;
import com.sky.checkutil.javadoc.JavadocReader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 检测工具
 *
 * @author: hjy
 * @create: 2023-12-28 14:43
 **/
public class CheckUtil {

    /**
     * 检测类、方法注释并导出结果
     *
     * @param checkParam
     */
    public static String checkClassAndMethodNote(CheckParam checkParam) {
        String res = "检测成功";
        if (checkParam.folderPath == null) {
            return "检测失败：请输入检测文件夹";
        }
        List<CheckVO> checkVOList = new ArrayList<>();
        //获取文件夹下的java文件路径
        List<String> javaFilePaths = FileUtil.getJavaFilePaths(checkParam);
        for (String path : javaFilePaths) {
            //读取文件
            ExtClassDoc doc = JavadocReader.read(path);
            if (doc != null) {
                //检测
                List<CheckVO> list = doc.checkClassAndMethodNote(checkParam);
                if (list.size() > 0) {
                    checkVOList.addAll(list);
                }
            }
        }

        File excelFile = new File(checkParam.exportPath);
        //判断文件是否存在，不存在则创建一个Excel文件
        if (!excelFile.exists()) {
            try {
                excelFile.createNewFile();//创建一个新的文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //导出过滤检测结果
        if (checkParam.result != null && !"".equals(checkParam.result)) {
            checkVOList = checkVOList.stream().filter(vo -> checkParam.result.equals(vo.getResult())).collect(Collectors.toList());
        }
        //导出
        EasyExcel.write(excelFile, CheckVO.class)
                .sheet("检测内容表格")
                .registerWriteHandler(new CustomCellWriteHeightConfig())
                .doWrite(checkVOList);
        return res;
    }

    public static void main(String[] args) {
        //String folderPath = "D:\\IdeaProjects\\yongyou\\gzltqdt\\gzltqdt-be\\dev-gzltqdt-app\\src\\main\\java\\com\\yonyou\\ucf\\mdf\\app\\service";
        //String folderPath = "D:\\IdeaProjects\\yongyou\\gzltqdt\\gzltqdt-be";
        String folderPath = "D:\\IdeaProjects\\yongyou\\gz-tyre-os";

        String exportPath = "C:\\Users\\hjy\\Desktop\\渠道通脚手架（gz-tyre-os）检测注释结果.xlsx";
        long startTime = System.currentTimeMillis();
        CheckParam checkParam = CheckParam.builder()
                .folderPath(folderPath)
                .exportPath(exportPath)
                .checkBelowFolder(true)
                .build();
        String res = checkClassAndMethodNote(checkParam);
        long endTime = System.currentTimeMillis();
        System.out.println("检测耗时：" + (endTime - startTime) / 1000 + "秒," + res);
    }
}
